import java.awt.*;
import java.util.Random;

public class FoodObj extends GameutilsOBJ {

    //随机函数
    Random r = new Random();

    public FoodObj() {
        super();
    }

    public FoodObj(Image img, int x, int y, GameWin frame) {
        super(img, x, y, frame);
    }

    //获取食物 - 专门用于初始化
    public FoodObj getFood(){
        if (this.frame == null || this.frame.headObj == null) {
            return new FoodObj(GameUtils.foodImg, 150, 150, this.frame);
        }

        int newX, newY;
        boolean validPosition;

        do {
            newX = r.nextInt(20) * 30;
            newY = 30 + r.nextInt(18) * 30;
            validPosition = true;

            // 检查是否与蛇头重叠
            if (newX == frame.headObj.x && newY == frame.headObj.y) {
                validPosition = false;
                continue;
            }

            // 检查是否与蛇身重叠
            for (BodyObj body : frame.bodyObjList) {
                if (newX == body.x && newY == body.y) {
                    validPosition = false;
                    break;
                }
            }

            // 检查是否与其他食物重叠（第四关专用）
            if (GameUtils.level == 4) {
                for (FoodObj food : frame.foodList) {
                    if (food != null && newX == food.x && newY == food.y) {
                        validPosition = false;
                        break;
                    }
                }
            }

        } while (!validPosition);

        return new FoodObj(GameUtils.foodImg, newX, newY, this.frame);
    }

    // ========== 新增：专门用于第四关生成新食物的方法 ==========
    public FoodObj getFoodForLevel4(GameWin frame) {
        int newX, newY;
        boolean validPosition;

        do {
            newX = r.nextInt(20) * 30;
            newY = 30 + r.nextInt(18) * 30;
            validPosition = true;

            // 检查是否与蛇头重叠
            if (newX == frame.headObj.x && newY == frame.headObj.y) {
                validPosition = false;
                continue;
            }

            // 检查是否与蛇身重叠
            for (BodyObj body : frame.bodyObjList) {
                if (newX == body.x && newY == body.y) {
                    validPosition = false;
                    break;
                }
            }

            // 检查是否与其他食物重叠
            for (FoodObj food : frame.foodList) {
                if (food != null && newX == food.x && newY == food.y) {
                    validPosition = false;
                    break;
                }
            }

        } while (!validPosition);

        return new FoodObj(GameUtils.foodImg, newX, newY, frame);
    }

    @Override
    public void paintSelf(Graphics g) {
        super.paintSelf(g);
    }
}